import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"

const initialState = {
  count: 0,
  msg: "hello world",
  data: {}
}

// 异步操作
function mockRequest() {
  return new Promise<object>((resolve, reject) => {
    setTimeout(() => {
      resolve({
        msg: "服务端请求数据"
      })
    }, 1500);
  });
}
export const fetchRquestAction = createAsyncThunk("fetchRquestAction", async (extraParams, { getState, dispatch }) => {
  let res = await mockRequest()
  // 通过 dispatch 去修改数据
  return res
})

const counterSlice = createSlice({
  name: "counter",
  initialState: initialState,
  reducers: {
    // 自动返回出新的 state
    incAction: (state, action) => {
      state.count += action.payload
    },
    decAction: (state, action) => {
      state.count -= action.payload
    }
  },
  extraReducers: (builder) => {
    builder.addCase(fetchRquestAction.pending, (state, action) => {
      console.log('fetchRquestAction pending');
    }).addCase(fetchRquestAction.fulfilled, (state, { payload }) => {
      state.data = payload
    })
  }
})

export const { incAction, decAction } = counterSlice.actions
export default counterSlice.reducer
